package com.example.concurrentprogramming8016.blockingqueue;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author liyanhao
 * @Date 2023-01-07 21:11
 * Delayed元素的无界阻塞队列，其中的元素只有在其延迟到期时才能被获取
 */
public class DelayQueueDemo {

    //可以用来执行定时任务
    static DelayQueue<MyTask> taskDelayQueue = new DelayQueue<>();

    static class MyTask implements Delayed {
        String name;
        long runningTime;

        public MyTask(String name, long runningTime) {
            this.name = name;
            this.runningTime = runningTime;
        }


        @Override
        public int compareTo(Delayed o) {
            long td = this.getDelay(TimeUnit.MILLISECONDS);
            long od = o.getDelay(TimeUnit.MILLISECONDS);
            return Long.compare(td, od);
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(
                    runningTime - System.currentTimeMillis(),
                    TimeUnit.MILLISECONDS);
        }

        @Override
        public String toString() {
            return name + " - " + runningTime;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        long now = System.currentTimeMillis();
        MyTask t1 = new MyTask("t1", now + 6000);
        MyTask t2 = new MyTask("t2", now + 4000);
        MyTask t3 = new MyTask("t3", now + 3000);
        MyTask t4 = new MyTask("t4", now + 2000);
        MyTask t5 = new MyTask("t5", now + 5000);
        MyTask t6 = new MyTask("t6", now + 1000);

        taskDelayQueue.add(t1);
        taskDelayQueue.add(t2);
        taskDelayQueue.add(t3);
        taskDelayQueue.add(t4);
        taskDelayQueue.add(t5);
        taskDelayQueue.add(t6);

        for (int i = 0; i < 6; i++) {
            System.out.println(taskDelayQueue.take());
        }

    }
}
